package com.mojo.concurrent.concurrent_06_future;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

/**
 * CompletableFuture使用示例
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class CompletableFutureDemo01 {
    public static void main(String[] args) {
        //newInstance();
        //processAsyncResult();
        processException();
    }

    //异常处理
    private static void processException() {
        CompletableFuture<Object> future = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                if (true) {
                    throw new RuntimeException("运行异常");
                }
                return "success";
            }
        });
        try {
            System.out.println(future.handle((res, ex) -> {
                if (ex != null) {
                    System.out.println(ex.getMessage());
                }
                return res != null ? res : "结果";
            }).get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }

    }

    //处理异步计算的结果
    private static void processAsyncResult() {

    }

    //创建实例的方式
    private static void newInstance() {
        // new 关键字创建，可等同于FutureTask
        CompletableFuture<Object> future = new CompletableFuture<>();
        //异步操作不关心结果，静态方法
        CompletableFuture<Void> asyncFuture = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                System.out.println("async");
            }
        });
        //异步操作需要结果，静态工厂方法
        CompletableFuture<Object> supplyFuture = CompletableFuture.supplyAsync(new Supplier<Object>() {
            @Override
            public Object get() {
                return new Random().nextInt(100);
            }
        });
    }
}
